package com.lkk.cg.service.impl;

import com.lkk.cg.base.DaoSupportImpl;
import com.lkk.cg.domain.DailyStatistics;
import com.lkk.cg.service.DailyStatisticsService;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by lkk on 2014/12/24.
 */
@Transactional
public class DailyStatisticsServiceImpl extends DaoSupportImpl<DailyStatistics> implements DailyStatisticsService {
    public void increment() {
        DailyStatistics statistics = getByDate(new Date());
        statistics.setCount(statistics.getCount() + 1);
        update(statistics);
    }

    public long countTodayDownload() {
        DailyStatistics statistics = getByDate(new Date());
        return statistics.getCount();
    }

    public long countTotalDownload() {
        Session session = getSession();
        Query query = session.createQuery("select sum(s.count) FROM DailyStatistics s");
        return (Long) (query.uniqueResult());
    }

    public DailyStatistics getByDate(Date date) {
        Session session = getSession();
        Query query = session.createQuery("FROM DailyStatistics s where s.date = :today")
                .setParameter("today", new Date());
        DailyStatistics todayStatistics = (DailyStatistics) query.uniqueResult();

        if (todayStatistics == null) {
            todayStatistics = new DailyStatistics();
            todayStatistics.setDate(new Date());
            todayStatistics.setCount(0);
            session.save(todayStatistics);
        }
        return todayStatistics;
    }
}
